import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class Message {
    //这几个属性必须设置成public
    //如果设置private，必须生成public 的 getter 和 setter！！
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    private List<Message> messageList = new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过这个方法来处理 ”获取所有的留言消息“
        //需要返回一个json字符串数组，jackson直接帮我们处理好了格式
        String respString = objectMapper.writeValueAsString(messageList);
        //最后把这个字符串数字写回响应即可
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(respString);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过这个方法来处理 ”提交新消息“
        //使用这个对象直接读取传过来的流对象，之后转化成一个Message的类型
        Message message = objectMapper.readValue(req.getInputStream(),Message.class);
        messageList.add(message);//然后把这个消息存放起来，存放到数组中
        System.out.println("消息提交成功！" + message);

        //响应只是返回 200 报文，body为空，此时不需要处理响应，默认返回的就是200
    }
}
